define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'school/student/index' + location.search,
                    add_url: 'school/student/add',
                    edit_url: 'school/student/edit',
                    del_url: 'school/student/del',
                    multi_url: 'school/student/multi',
                    import_url: 'school/student/import',
                    table: 'student',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                exportTypes: ['excel'],
                // exportDataType: "selected",
                exportOptions:{
                    // ignoreColumn: [0,1,9,10,11],  //忽略某一列的索引
                    fileName: '学员信息表',  //文件名称设置
                    worksheetName: 'ttttt',  //表格工作区名称
                    // tableName: '总台帐报表',
                    excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
                    mso: {                            // MS Excel and MS Word related options
                        fileFormat:        'xls',   // xlshtml = Excel 2000 html format
                        // xmlss = XML Spreadsheet 2003 file format (XMLSS)
                        // xlsx = Excel 2007 Office Open XML format
                        onMsoNumberFormat: null,        // Excel 2000 html format only. See readme.md for more information about msonumberformat
                        pageFormat:        'a4',        // Page format used for page orientation
                        pageOrientation:   'portrait',  // portrait, landscape (xlshtml format only)
                        rtl:               false,       // true = Set worksheet option 'DisplayRightToLeft'
                        styles:            [],          // E.g. ['border-bottom', 'border-top', 'border-left', 'border-right']
                        worksheetName:     ''
                    },
                    // onMsoNumberFormat: DoOnMsoNumberFormat
                },
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name')},
                        {field: 'student_number', title: __('Student_number')},
                        {field: 'work_station_dict', title: __('Work_station_dict'), searchList: Config.workStationDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'exametime', title: __('Exametime'),visible:false},
                        {field: 'major_level_dict', title: __('Major_level_dict'), searchList: Config.majorLevelDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'major_id', title: __('Major_id'),searchList: $.getJSON("school/major/searchlist"),visible:false},//只用于查询（不显示列表），查询是where必须是字段名.admin\controller\school
                        {field: 'major_id_text', title: __('Major_id'),operate:false},//只用于展示，不显示在条件查询中
                        {field: 'student_type_dict', title: __('Student_type_dict'), searchList: Config.studentTypeDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'student_id_code', title: __('Student_id_code')},
                        {field: 'student_sex', title: __('Student_sex'), searchList: {"0":__('Student_sex 0'),"1":__('Student_sex 1')}, formatter: Table.api.formatter.normal},
                        {field: 'student_birthday', title: __('Student_birthday'), operate:'RANGE', addclass:'datetimerange',visible:false},
                        {field: 'student_nation', title: __('Student_nation')},
                        {field: 'student_birth_localtion', title: __('Student_birth_localtion')},
                        {field: 'student_political_status_dict', title: __('Student_political_status_dict'), searchList: Config.studentPoliticalStatusDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'student_mail_address', title: __('Student_mail_address'),visible:false},
                        {field: 'student_postcode', title: __('Student_postcode'),visible:false},
                        {field: 'student_tel', title: __('Student_tel'),visible:false},
                        {field: 'studentimage', title: __('Studentimage'), events: Table.api.events.image, formatter: Table.api.formatter.image,visible:false},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3')}, formatter: Table.api.formatter.status},
                        //{field: 'student_login_pwd', title: __('Student_login_pwd')},
                        {field: 'student_last_level_dict', title: __('Student_last_level_dict'), searchList: Config.studentLastLevelDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'student_last_school', title: __('Student_last_school'),visible:false},
                        {field: 'student_work_unit', title: __('Student_work_unit'),visible:false},
                        {field: 'student_work_unit_tel', title: __('Student_work_unit_tel'),visible:false},
                        // {field: 'scoure_politics', title: __('Scoure_politics'), operate:'BETWEEN'},
                        // {field: 'scoure_chinese', title: __('Scoure_chinese'), operate:'BETWEEN'},
                        // {field: 'scoure_math', title: __('Scoure_math'), operate:'BETWEEN'},
                        // {field: 'scoure_english', title: __('Scoure_english'), operate:'BETWEEN'},
                        // {field: 'scoure_add', title: __('Scoure_add'), operate:'BETWEEN'},
                        // {field: 'scoure_sum', title: __('Scoure_sum'), operate:'BETWEEN'},
                        {field: 'student_last_type_dict', title: __('Student_last_type_dict'), searchList: Config.studentLastTypeDictList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        // {field: 'student_last_starttime', title: __('Student_last_starttime'), operate:'RANGE', addclass:'datetimerange'},
                        // {field: 'student_last_endtime', title: __('Student_last_endtime'), operate:'RANGE', addclass:'datetimerange'},
                        // {field: 'student_remark', title: __('Student_remark')},
                        // {field: 'create_by', title: __('Create_by')},
                        // {field: 'update_by', title: __('Update_by')},
                        // {field: 'remark', title: __('Remark')},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'studentExportExcel', title: __('学籍卡导出'), table: table,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: __('导出'),
                                    title: __('导出'),
                                    classname: 'btn btn-xs btn-warning',
                                    icon: 'fa fa-folder-o',
                                    url: 'school/student/exportStudent'
                                }
                            ],
                            formatter: Table.api.formatter.buttons,
                            events: Table.api.events.operate},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $(".btn-download").on("click",function(){
                window.location.href = "/excel_template/学员信息导入模板.xls"; 
            });
            $(".btn-export").on("click",function(){

                var ids = $('#table').bootstrapTable('getSelections', null);
                var idstext = '';
                if (ids.length == 0) {
                    alert("请选择学员");
                  } else {
                ids.forEach(element => {
                    idstext += element.id + ",";
                });
                let loadIndex = layer.load();
                idstext += "0";
                var fileName = "export.zip";//设置下载时候的文件名
                var url = "student/exportStudent?ids=" + idstext;
                var xhr = new XMLHttpRequest();
                //设置响应类型为blob类型
                xhr.responseType = "blob";
                xhr.onload = function () {
                    layer.close(loadIndex);
                    if (this.status === 200) {
                        //获取响应文件流　　
                        var blob = this.response;
                        var reader = new FileReader();
                        reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                        reader.onload = function (e) {
                            // 转换完成，创建一个a标签用于下载
                            var a = document.createElement('a');
                            a.download = fileName;
                            a.href = e.target.result;
                            $("body").append(a);    // 修复firefox中无法触发click
                            a.click();
                            $(a).remove();
                        };
                        /*var aElem = document.createElement("a");
                        //将文件流保存到a标签
                        aElem.href = window.URL.createObjectURL(blob);
                        aElem.id = "download";
                        aElem.download = fileName;
                        aElem.onload = function (e) {
                            window.URL.revokeObjectURL(aElem.href);
                        };
                        $("body").append(aElem);
                        $("#download")[0].click();*/

                        /*layer.confirm('文件已导出, 立即下载？', function (index) {

                            layer.close(index);
                        });*/
                    }
                }

                xhr.open("post", url, true);
                xhr.send();

                // Fast.api.ajax({
                //     url : "school/student/exportStudent?ids=" + idstext,
                //     success: function (data) {
                //         debugger
                //     }
                // })
                // window.location.href = "student/exportStudent?ids=" + idstext;
                // console.log("222");
            }
            });
            
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'school/student/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'school/student/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'school/student/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});